<template>
  <div class="">
    <div class="center">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="名称" prop="name">
          <el-input
            maxlength="16"
            v-model.trim="queryParams.name"
            placeholder="请输入"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            maxlength="16"
            v-model.trim="queryParams.remark"
            placeholder="请输入"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" fit-input-width clearable placeholder="请选择">
            <el-option label="进行中" value="1"></el-option>
            <el-option label="已失效" value="2"></el-option>
            <el-option label="已过期" value="3"></el-option>
            <el-option label="待开始" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市标签" prop="cityName">
          <el-select
            v-model="queryParams.cityName"
            @change="handleQuery"
            fit-input-width
            placeholder="请选择"
          >
            <el-option
              v-for="item in cityNameOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            icon="Plus"
            type="primary"
            @click="handleAdd"
            v-hasPermi="['marketing:raffle:add']"
          >
            新建
          </el-button>
        </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" size="default" index :data="dataList">
        <el-table-column
          label="名称"
          min-width="150px"
          align="center"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column
          label="备注"
          min-width="150px"
          align="center"
          prop="remark"
          show-overflow-tooltip
        />
        <el-table-column label="城市标签" align="center" prop="cityName" show-overflow-tooltip />
        <el-table-column label="参与人数" align="center">
          <template #default="{ row }">
            <el-link :underline="false" type="primary" @click="handleJoin(row)">{{
              row.clientNum
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100px" align="center" prop="status">
          <!-- :[0:删除,1:进行中,2:已失效,3:已过期,4:待开始] -->
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 1
                  ? 'primary'
                  : row.status === 2
                  ? 'danger'
                  : row.status === 3
                  ? 'info'
                  : 'warning'
              "
              >{{
                row.status === 1
                  ? '进行中'
                  : row.status === 2
                  ? '失效'
                  : row.status === 3
                  ? '已过期'
                  : '待开始'
              }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="140px" align="center" prop="createTime" />
        <el-table-column label="活动时间" min-width="130px" align="center" prop="surplusCount">
          <template #default="{ row }">
            {{ row.startTime + '-' + row.endTime }}
          </template>
        </el-table-column>
        <el-table-column label="剩余库存" align="center">
          <template #default="{ row }">
            <el-link :underline="false" type="primary" @click="handleSurplus(row.id)">{{
              row.surplusCount
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px" fixed="right">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; justify-content: center">
              <!-- 失效或者过期展示删除 -->
              <el-link
                v-hasPermi="['marketing:raffle:delete']"
                v-if="row.status === 2 || row.status === 3"
                style="margin-right: 6px"
                :underline="false"
                type="danger"
                @click="handleDelete(row)"
                >删除</el-link
              >
              <el-link
                v-hasPermi="['marketing:raffle:expire']"
                v-if="row.status === 1 || row.status === 4"
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleExpire(row)"
                >失效</el-link
              >
              <el-link
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleDetail(row)"
                >参与详情</el-link
              >
              <el-link
                v-hasPermi="['marketing:raffle:edit']"
                :underline="false"
                type="primary"
                @click="handleEdit(row)"
                >编辑</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 新建 -->
    <addDialog ref="addRef" :title="title" @refresh="getList" />
    <!-- 参与人数 -->
    <joinDialog ref="joinDialogRef" />
    <!-- 剩余库存 -->
    <surplusDialog ref="surplusRef" />
    <!-- 参与详情 -->
    <JoinDetail ref="joinDetailRef" />
  </div>
</template>

<script setup>
import addDialog from './cpts/addDialog.vue'
import joinDialog from './cpts/joinDialog.vue'
import surplusDialog from './cpts/surplusDialog.vue'
import useGlobalStore from '@/store/modules/global'
import JoinDetail from './cpts/joinDetail.vue'
import { ElMessage } from 'element-plus'
import { checkRaffleApi, getRaffleListApi, updateRaffleApi } from '@/api/marketing/raffle'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  return globalStore.myCityList
})

const title = ref('')
const queryRef = ref(null)
const showSearch = ref(true)
const route = useRoute()

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  remark: '',
  name: '',
  status: '',
  cityName: ''
})

const total = ref(0)
const dataList = ref([])
const loading = ref(false)

function getList() {
  loading.value = false
  const params = {
    ...queryParams,
    startTime: queryParams.time?.length ? queryParams.time[0] : '',
    endTime: queryParams.time?.length ? queryParams.time[1] : ''
  }
  delete params.time
  getRaffleListApi(params)
    .then((res) => {
      loading.value = false
      dataList.value = res?.data?.rows || []
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
      dataList.value = []
      total.value = 0
    })
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}

// 新建
const addRef = ref(null)
function handleAdd() {
  checkRaffleApi({ cityName: queryParams.cityName }).then((res) => {
    if (res?.data) {
      title.value = '抽奖设置'
      addRef.value.init(queryParams.cityName)
    } else {
      ElMessage.error('当前已有进行中的活动，无法新建，请结束后再创建')
    }
  })
}

// ================= 参与人数 =======================
const joinDialogRef = ref(null)
function handleJoin(row) {
  joinDialogRef.value.init(row, queryParams.cityName)
}

// ================ 剩余库存 ==================
const surplusRef = ref(null)
function handleSurplus(id) {
  surplusRef.value.init(id, queryParams.cityName)
}

// 编辑
function handleEdit(row) {
  title.value = '抽奖详情'
  addRef.value.init(row.cityName, row.id, true)
}

// 失效2 删除0
// 删除
function handleDelete(row) {
  ElMessageBox.confirm('抽奖活动记录将会被删除', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      updateRaffleApi({ id: row.id, status: 0 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        handleQuery()
      })
    })
    .catch(() => {})
}
// 失效
function handleExpire(row) {
  ElMessageBox.confirm('抽奖活动将会被强制失效', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      updateRaffleApi({ id: row.id, status: 2 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        handleQuery()
      })
    })
    .catch(() => {})
}

// ================= 参与详情 ============
const joinDetailRef = ref(null)
function handleDetail(row) {
  joinDetailRef.value.init(row)
}

onMounted(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  getList()
})
</script>

<style lang="scss" scoped>
.center {
  padding: 20px;
  .actions {
    align-items: center;
    display: flex;
  }
}
.name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
